<?php

namespace app\common\controller\xilujob;

use app\common\library\Auth;
use app\common\model\xilujob\Area;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\JobApply;
use app\common\model\xilujob\JobInterview;
use app\common\model\xilujob\Member;
use app\common\model\xilujob\Resume;
use app\common\model\xilujob\ResumeActionLog;
use app\common\model\xilujob\ResumeDownload;
use app\common\model\xilujob\SiteCity;
use app\common\model\xilujob\XilujobUser;
use app\index\model\xilujob\UserActiveLog;
use think\Config;
use think\Controller;
use think\Db;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Validate;
use function fast\array_get;

/**
 * 前台控制器基类
 */
class Xilujob extends Controller
{
    protected $model;
    /**
     * 布局模板
     * @var string
     */
    protected $layout = 'xilujob';

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['_empty'];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = false;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = false;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'user_id';

    /**
     * 城市
     */
    protected $city;

    /**
     * 定义action的用户组权限, 若action未在此定义，意味着所有用户组都可用
     * @var string|array
     */
    protected $restrictedActions = [
        //example
        // '$actionName' => [1,2,3,4]  数组里写允许调用的用户组id
    ];

    protected $noNeedEnterpriseAudit = [];
    //默认城市
    const DEFAULT_CITY_ID = 802; //上海

    protected $company = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    public function _initialize()
    {
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        // 如果有使用模板布局
        if ($this->layout) {
            $this->view->engine->layout('layout/' . $this->layout);
        }
        $this->auth = Auth::instance();

        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $cityId = cookie('current_city') ? : self::DEFAULT_CITY_ID;
        $this->city = Area::alias('a')->join('xilujob_site_city c','a.id=c.city_id')->where('a.id',$cityId)
            ->field('a.id,name,shortname')->find();
        if(!$this->city) {
            $this->city = Area::where('id',self::DEFAULT_CITY_ID)->field('id,name,shortname')->find();
        }

        // 定义是否Dialog请求
        !defined('IS_DIALOG') && define('IS_DIALOG', (input("dialog") || in_array($actionname,['download','batch_download'])) ? true : false);

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), 'user/login', ['need_login'=>1]);
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'));
                }
            }
            // 判断action是否有限制用户组使用
            if(isset($this->restrictedActions['*']) || isset($this->restrictedActions[$actionname])) {
                $user = $this->auth->getUser();
                $allowedGroups = array_get($this->restrictedActions, $actionname, []) ? : array_get($this->restrictedActions,'*', []);
                if($allowedGroups!=='*' && !in_array($user->group_id, $allowedGroups)) {
                    $targetGroupId = $allowedGroups[0];
                    $tip = $targetGroupId==XilujobUser::GROUP_MEMBER ? '个人用户':'企业用户';
                    $this->error(__("请切换到{$tip}身份使用"),'index/index', 403);
                }
            }
        } else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }

        $user = $this->auth->getUser();
        $this->view->assign('user', $user);
        //
        if($user) {
            $xiluuser = XilujobUser::get(['user_id'=>$user->id]);
            if($xiluuser){
                $now = time();
                $xiluuser->save(['actiontime'=>$now]);
                //每小时+1的活跃度
                if($xiluuser->group_id==XilujobUser::GROUP_MEMBER) {
                    $logType = 1;
                }else if ($xiluuser->group_id==XilujobUser::GROUP_COMPANY){
                    $logType = 2;
                }else{
                    $logType = -1;
                }
                $log = UserActiveLog::where('user_id',$user->id)->where('type', $logType)->order('active_time','desc')->find();
                $activeTime = $log ? $log->active_time : null;
                if(!$activeTime || $activeTime<$now-3600) {
                    UserActiveLog::create(['user_id'=>$user->id,'type'=>$logType,'active_time'=>$now]);
                }
                $message_count = $xiluuser->system_message + $xiluuser->personal_message + $xiluuser->activity_message;
                $this->assign('message_count', $message_count);
            }
            $this->view->assign('xilujobuser', $xiluuser);
        }

        //企业用户必须提交认证, 未提交或提交未通过时，跳转提交页面
        if(!isset($xiluuser) && !in_array($actionname, $this->noNeedEnterpriseAudit)){
            $this->error('您还未注册企业身份','xilujob.entry/entry?dialog=1');
        }
        elseif(isset($xiluuser) && in_array($xiluuser->group_id,[2,3]) && !in_array($actionname, $this->noNeedEnterpriseAudit)) {
            if (in_array($xiluuser->enterprise_model->audit_status,[0,3])){
                $this->error('您提交的企业资料未通过审核','xilujob.entry/entry?dialog=1');
            }else if($xiluuser->enterprise_model->audit_status == 2){
                $this->error('您提交的企业资料正在审核中...','xilujob.entry/entry?dialog=1');
            }
        }else if(isset($xiluuser) && $xiluuser->enterprise_group_id == 0 && !in_array($actionname, $this->noNeedEnterpriseAudit)){
            $this->error('您还不是企业用户','xilujob.entry/entry?dialog=1');
        }
        if($xiluuser){
            $this->company = CompanyProfile::get(['company_profile.user_id'=>$xiluuser->user_id],['enterpriseinfo']);
            $this->assign('company',$this->company);
        }

        //待处理简历数
        $apply_count = $interview_count = 0;
        if($this->auth->isLogin() && $this->company){
            $apply_count = db('xilujob_job_apply')->where('company_id',$this->company->id)->where('status',JobApply::STATUS_APPLY_SENT)->count()?:0;
            $interview_count = db('xilujob_job_interview')->where('company_id',$this->company->id)->where('status',JobInterview::STATUS_INTERVIEW_ACCEPTED)->count()?:0;
        }
        $this->assign('apply_count',$apply_count);
        $this->assign('interview_count',$interview_count);

        // 语言检测
        $lang = strip_tags($this->request->langset());

        $site = Config::get("site");

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages','pc_qq_service'])),
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => 'frontend/' . str_replace('.', '/', $controllername),
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang,
            'url_controller'       => $path,
        ];
        $config = array_merge($config, Config::get("view_replace_str"));
        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 配置信息后
        Hook::listen("config_init", $config);
        // 加载当前控制器语言包
        $this->loadlang($controllername);
        $this->assign('site', $site);
        $this->assign('config', $config);
        //城市
        $this->assign('site_cities', SiteCity::getAll());
        $this->assign('current_city', $this->city);

        //导航高亮
        $this->assign('nav_tag','');
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name =  Loader::parseName($name);
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 渲染配置信息
     * @param mixed $name  键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->param('__token__');

        //验证Token
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
            $this->error(__('Token verification error'), '', ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }

    /**
     * 企业主动消耗次数的提示消息
     */
    public function action_msg() {
        $type = $this->request->param('type','resume_view');
        switch($type){
            case "resume_view":
                #1.简历查看
                $resume_id = $this->request->param('resume_id');
                $resume_ids = $this->request->param('resume_ids');
                $count = 0;
                if($resume_id){
                    $resume = Resume::get($resume_id);
                    //先判断是否已获取过
                    $hasActionLog = ResumeActionLog::hasLog($this->company->id,$resume->user_id,$resume->id);
                    if(!$hasActionLog) $count = 1;
                }else{
                    $resume_ids = explode(',',$resume_ids);
                    foreach ($resume_ids as $resume_id){
                        $resume = Resume::get($resume_id);
                        //先判断是否已获取过
                        $hasActionLog = ResumeActionLog::hasLog($this->company->id,$resume->user_id,$resume->id);
                        if(!$hasActionLog){
                            $count++;
                        }
                    }
                }
                $availableNum = ResumeActionLog::getAvailableNum($this->company->id,$type);
                if($availableNum >= $count) {
                    $this->success("可以查看简历");
                }
                $this->error('您的简历查看次数已用尽，请前往购买套餐！');
                break;
            case "job_publish":
                #2.职位添加
                $jobHasActionNum = Job::getAvailableNum($this->company->id,$type);
                if($jobHasActionNum>0){
                    $this->success("可以发布职位");
                }
                $this->error('您的职位添加次数已用尽，请前往购买套餐！');
                break;
            case "interview":
                #3.面试邀请
                $resume_ids = $this->request->param('resume_ids');
                $count = 1;
                if($resume_ids){
                    $resume_ids_array = explode(',',$resume_ids);
                    $count = count($resume_ids_array);
                }
                $interviewHasActionNum = ResumeActionLog::getAvailableNum($this->company->id,$type);
                if($interviewHasActionNum < $count){
                    $this->error('您的剩余面试邀请次数不足以抵扣，请前往购买套餐！');
                }
                $this->success("可以邀请面试");
                break;
            case "refresh_job":
                #4.刷新职位
                $jobHasActionNum = Job::getAvailableNum($this->company->id,$type);
                if($jobHasActionNum>0){
                    $this->success("可以发布职位");
                }
                $this->error('您的职位刷新次数已用尽，请前往购买套餐！');
                break;
        }
    }

    public function _empty($name)
    {
        //$this->redirect('index/user/login');
    }


    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }

        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $arrSearch = [];
            foreach (explode(" ", $search) as $ko) {
                $arrSearch[] = '%'.$ko.'%';
            }
            $where[] = [implode("|", $searcharr), "LIKE", $arrSearch];
        }

        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        // dump($where);exit;
        return [$where, $sort, $order, $offset, $limit,$page];
    }
}
